package com.mlh.exception;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class MyExceptionHandler {

    //编写方法，模拟异常
    //如果我们不处理异常，则由tomcat默认机制来处理
    @RequestMapping("/testException01")
    public String test01 (Integer num){
        int i = 9/num;
        return"success";
    }

    // localException方法处理局部异常
    // 这里处理ArithmeticException.class , NullPointerException.class
    @ExceptionHandler({ArithmeticException.class, NullPointerException.class})
    public String localException(Exception exception, HttpServletRequest request){
        System.out.println("异常信息是="+exception);
        request.setAttribute("reason",exception.getMessage());
        return "exception_mes";
    }

    @RequestMapping(value = "/testGlobalException")
    public String global(){
        //1.这里我们模拟了一个异常NumberFormatException
        //2.该异常没有在局部异常处理，按照异常处理机制，就会交给全局异常处理类处理
        int num = Integer . parseInt("hello");
        return "success";
    }

    //自定义异常抛出
    @RequestMapping(value = "/testException02")
    public String test02(){
        throw new AgeException();
    }

    @RequestMapping(value = "/testException03")
    public String test03() {
        int[] arr = new int[]{3, 9, 10, 190};
        // 抛出一个数组越界的异常ArrayIndexOutOfBoundsException
        System.out.println(arr[90]);
        return "success";
    }

    //如果发生J没有归类的异常，可以给出统一提示页面
    @RequestMapping(value = "/testException04")
    public String test04() {
        String str = "hello";
        // 这里会抛出StringIndexOutOfBoundsException
        char C = str.charAt(10);
        return "success";
    }


}
